package com.blb.permission_ms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blb.permission_ms.entity.Permission;
import com.blb.permission_ms.entity.Role;
import com.blb.permission_ms.entity.User;
import com.blb.permission_ms.mapper.UserMapper;
import com.blb.permission_ms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Role> getRolesByUsername(String username) {
        return userMapper.selectRolesByUsername(username);
    }

    @Override
    public List<Permission> getPermissionByUsername(String username) {
        return userMapper.selectPermissionByUsername(username);
    }

    @Override
    public List<GrantedAuthority> getAuthoritiesByUsername(String username) {
        //查询所有的角色和权限
        List<Role> roles = userMapper.selectRolesByUsername(username);
        List<Permission> permissions = userMapper.selectPermissionByUsername(username);
        //连接到字符串中  ROLE_XXX,ROLE_XXX,XXX,XX
        StringBuffer stringBuffer = new StringBuffer();
        roles.forEach(role -> stringBuffer.append("ROLE_" + role.getName() + ","));
        permissions.forEach(permission -> stringBuffer.append(permission.getName() + ","));
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        //如果不为空，将用户账号密码包装到UserDetails中返回 参数：账号，密码，权限
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(stringBuffer.toString());
        return authorities;
    }

    @Override
    public List<Permission> getPermissionMenuByUsername(String username) {
        return userMapper.selectPermissionMenuByUsername(username);
    }
}
